package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.CollectReportVO;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.UserWorkVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;



    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }
        //如果是投放工单，状态为运营则抛出异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_DEPLOY && vm.getVmStatus() == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("投放工单，设备状态不能为运营状态");
        }
        //如果是补货工单，状态不是运营状态则抛出异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY && vm.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("补货工单，设备状态只能为运营状态");
        }
        //如果是撤机工单，状态不是运营状态则抛出异常
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_REVOKE && vm.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("撤机工单，设备状态只能为运营状态");
        }
        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }
        //校验这台设备是否有未完成的同类型工单，如果存在则不能创建。
        int count = count(Wrappers.<TaskEntity>lambdaQuery().eq(TaskEntity::getInnerCode, taskViewModel.getInnerCode()).eq(TaskEntity::getProductTypeId, taskViewModel.getProductType()).in(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_CREATE, VMSystem.TASK_STATUS_PROGRESS));
        if (count != 0){
            throw new LogicException("该工单已存在");
        }
        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(  vm.getRegionId() );//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
        updateRedisZSet(taskEntity,1);
        return true;
    }

    /**
     * 更新工单量列表
     * @param taskEntity
     */
    private void updateRedisZSet(TaskEntity taskEntity,int score) {
        String roleCode = "1003";
        if (taskEntity.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)){
            roleCode = "1002";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId()
                + "." + roleCode;
        redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score);
    }


    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date +  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }


    @Override
    public boolean accept(Integer userId, Long id) {
        TaskEntity task = this.getById(id);  //查询工单
        if (task == null){
            throw new LogicException("该工单不存在");
        }
        //当前工单的执行人是否为当前登录用户
        if (userId != task.getUserId()){
            throw new LogicException("该工单未分配给登录用户");
        }
        //当前工单是否是待处理状态，如果不是则抛出异常。
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE){
            throw new LogicException("该工单状态异常，无法接收该工单");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Integer userId, Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        if (task == null){
            throw new LogicException("该工单不存在");
        }
        //当前工单的执行人或创建人是否为当前登录用户，如果不是则抛出异常。
        if (userId != task.getUserId() && userId != task.getAssignorId()){
            throw new LogicException("该工单未分配给登录用户或该工单不是登录用户创建的");
        }
        //当前工单是否是未结束状态，如果是已完成或已取消则抛出异常。
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL || task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH){
            throw new LogicException("该工单状态异常，无法取消该工单");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(cancelVM.getDesc());
        updateRedisZSet(task,-1);
        return this.updateById(task);
    }


    @Autowired
    private MqttProducer mqttProducer;


    @Override
    public boolean completeTask(Integer userId, long id) {
        TaskEntity task = this.getById(id);
        if (task == null){
            throw new LogicException("该工单不存在");
        }
        //当前工单的执行人是否为当前登录用户
        if (userId != task.getUserId()){
            throw new LogicException("该工单未分配给登录用户");
        }
        //当前工单是否是进行中状态，如果不是则抛出异常。
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_PROGRESS){
            throw new LogicException("该工单状态异常，无法完成该工单");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(task);
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || task.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE){
            operationsTaskSendMQ(task);
        }
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            supplyTaskSendMQ(task);
        }
        return true;
    }

    @Override
    public int getLastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1003";
        if (isRepair){
            roleCode = "1002";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + regionId
                + "." + roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 0);
        return (Integer)set.stream().collect(Collectors.toList()).get(0);
    }

    @Override
    public List<TaskReportInfoVO> taskReportInfo(LocalDateTime start, LocalDateTime end) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda().between(TaskEntity::getUpdateTime,start,end);
        List<TaskEntity> taskEntityList = this.list(qw);

        TaskReportInfoVO repairerTaskReportInfo = new TaskReportInfoVO();
        repairerTaskReportInfo.setTotal(0);
        repairerTaskReportInfo.setCompletedTotal(0);
        repairerTaskReportInfo.setCancelTotal(0);
        repairerTaskReportInfo.setProgressTotal(0);
        repairerTaskReportInfo.setWorkerCount(userService.getRepairerCount());
        repairerTaskReportInfo.setRepair(true);
        repairerTaskReportInfo.setDate(LocalDateTime.now().toString());

        TaskReportInfoVO operatorTaskReportInfo = new TaskReportInfoVO();
        operatorTaskReportInfo.setTotal(0);
        operatorTaskReportInfo.setCompletedTotal(0);
        operatorTaskReportInfo.setCancelTotal(0);
        operatorTaskReportInfo.setProgressTotal(0);
        operatorTaskReportInfo.setWorkerCount(userService.getOperatorCount());
        operatorTaskReportInfo.setRepair(false);
        operatorTaskReportInfo.setDate(LocalDateTime.now().toString());

        taskEntityList.forEach(taskEntity -> {
            if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
                operatorTaskReportInfo.setTotal(operatorTaskReportInfo.getTotal() + 1);
                switch (taskEntity.getTaskStatus()){
                    case 1:
                    case 2:
                        operatorTaskReportInfo.setProgressTotal(operatorTaskReportInfo.getProgressTotal() + 1);
                        break;
                    case 3:
                        operatorTaskReportInfo.setCancelTotal(operatorTaskReportInfo.getCancelTotal() + 1);
                        break;
                    case 4:
                        operatorTaskReportInfo.setCompletedTotal(operatorTaskReportInfo.getCompletedTotal() + 1);
                        break;
                    default:
                        log.info("工单状态参数错误");
                }
            }else {
                repairerTaskReportInfo.setTotal(repairerTaskReportInfo.getTotal() + 1);
                switch (taskEntity.getTaskStatus()){
                    case 1:
                    case 2:
                        repairerTaskReportInfo.setProgressTotal(repairerTaskReportInfo.getProgressTotal() + 1);
                        break;
                    case 3:
                        repairerTaskReportInfo.setCancelTotal(repairerTaskReportInfo.getCancelTotal() + 1);
                        break;
                    case 4:
                        repairerTaskReportInfo.setCompletedTotal(repairerTaskReportInfo.getCompletedTotal() + 1);
                        break;
                    default:
                        log.info("工单状态参数错误");
                }
            }
        });
        List<TaskReportInfoVO> taskReportInfoVOList = new ArrayList<>();
        taskReportInfoVOList.add(operatorTaskReportInfo);
        taskReportInfoVOList.add(repairerTaskReportInfo);
        return taskReportInfoVOList;
    }

    @Override
    public List<CollectReportVO> collectReport(LocalDate start, LocalDate end) {
        List<CollectReportVO> collectReportVOList = new ArrayList<>();
        while (!start.isAfter(end)){
            CollectReportVO collectReportVO = collectReportByDate(start);
            collectReportVOList.add(collectReportVO);
            start = start.plusDays(1);
        }
        return collectReportVOList;
    }

    @Autowired
    private TaskDao taskDao;

    @Override
    public List<UserWorkVO> userWorkTop10(LocalDate start, LocalDate end, boolean isRepair, Long regionId) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.select("user_name userName","count(user_id) count");
        qw.lambda()
                .between(TaskEntity::getUpdateTime,LocalDateTime.of(start, LocalTime.MIN),LocalDateTime.of(end, LocalTime.MAX))
                .eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH);
        if (isRepair){
            qw.lambda().ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else{
            qw.lambda().eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }
        if (regionId != 0){
            qw.lambda().eq(TaskEntity::getRegionId,regionId);
        }
        qw.groupBy("user_name")
                .orderByDesc("count")
                .last("limit 10");
        List<Map<String, Object>> maps = taskDao.selectMaps(qw);
        List<UserWorkVO> userWorkVOList = new ArrayList<>();
        maps.forEach(map -> {
            UserWorkVO userWorkVO = new UserWorkVO();
            userWorkVO.setUserName((String)map.get("userName"));
            userWorkVO.setWorkCount((int)((long)map.get("count")));
            userWorkVOList.add(userWorkVO);
        });
        return userWorkVOList;
    }

    @Override
    public UserWorkVO userWork(LocalDateTime start, LocalDateTime end, Integer userId) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(TaskEntity::getUserId,userId)
                .between(TaskEntity::getUpdateTime,start,end);
        List<TaskEntity> taskEntityList = list(qw);
        UserWorkVO userWorkVO = new UserWorkVO();
        userWorkVO.setUserId(userId);
        userWorkVO.setWorkCount(0);
        userWorkVO.setProgressTotal(0);
        userWorkVO.setCancelCount(0);
        userWorkVO.setTotal(0);
        taskEntityList.forEach(taskEntity -> {
            userWorkVO.setTotal(userWorkVO.getTotal() + 1);
            switch (taskEntity.getTaskStatus()){
                case 1:
                case 2:
                    userWorkVO.setProgressTotal(userWorkVO.getProgressTotal() + 1);
                    break;
                case 3:
                    userWorkVO.setCancelCount(userWorkVO.getCancelCount() + 1);
                    break;
                case 4:
                    userWorkVO.setWorkCount(userWorkVO.getWorkCount() + 1);
                    break;
                default:
                    log.info("工单状态参数错误");
            }
        });
        return userWorkVO;
    }

    private CollectReportVO collectReportByDate(LocalDate start) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .between(TaskEntity::getUpdateTime,LocalDateTime.of(start, LocalTime.MIN),LocalDateTime.of(start, LocalTime.MAX));
        List<TaskEntity> taskEntityList = this.list(qw);
        CollectReportVO collectReportVO = new CollectReportVO();
        collectReportVO.setFinishCount(0);
        collectReportVO.setCancelCount(0);
        collectReportVO.setProgressCount(0);
        collectReportVO.setCollectDate(start);
        taskEntityList.forEach(taskEntity -> {
            switch (taskEntity.getTaskStatus()){
                case 1:
                case 2:
                    collectReportVO.setProgressCount(collectReportVO.getProgressCount() + 1);
                    break;
                case 3:
                    collectReportVO.setCancelCount(collectReportVO.getCancelCount() + 1);
                    break;
                case 4:
                    collectReportVO.setFinishCount(collectReportVO.getFinishCount() + 1);
                    break;
                default:
                    log.info("工单状态参数错误");
            }
        });

        return collectReportVO;
    }

    /**
     * 完成补货工单
     * @param task
     */
    private void supplyTaskSendMQ(TaskEntity task) {
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(task.getInnerCode());
        List<TaskDetailsEntity> list = taskDetailsService.list(Wrappers.<TaskDetailsEntity>lambdaQuery().eq(TaskDetailsEntity::getTaskId, task.getTaskId()));
        List<SupplyChannel> collect = list.stream().map(taskDetailsEntity -> {
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(taskDetailsEntity.getChannelCode());
            supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
            supplyChannel.setSkuId(taskDetailsEntity.getSkuId());
            supplyChannel.setSkuName(taskDetailsEntity.getSkuName());
            supplyChannel.setSkuImage(taskDetailsEntity.getSkuImage());
            return supplyChannel;
        }).collect(Collectors.toList());
        supplyContract.setSupplyData(collect);
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,supplyContract);
        } catch (JsonProcessingException e) {
            log.info("补货工单微服务发送消息失败");
            throw new LogicException("补货工单微服务发送消息失败");
        }

    }

    /**
     * 完成运维工单
     * @param task
     */
    private void operationsTaskSendMQ(TaskEntity task) {
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setTaskType(task.getProductTypeId());
        taskCompleteContract.setInnerCode(task.getInnerCode());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        } catch (JsonProcessingException e) {
            log.info("运维工单微服务发送消息失败");
            throw new LogicException("运维工单微服务发送消息失败");
        }

    }

}
